package datastructure.turnprint;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 15:25
 * @description:
 */
public class PrintNumber2 {
    private static int num;
    private static int MAX = 200000;
    private ReentrantLock lock = new ReentrantLock();

    public void print(int order) {
        while (true) {
            lock.lock();
            if (num >= MAX) {
                lock.unlock();//释放锁方便其他线程进入判断然后退出循环，可以用finally保证最终一定释放锁
                break;
            }
            if (num % 3 == order) {
                System.out.println(Thread.currentThread().getName() + ":" + num);
                num++;
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        PrintNumber2 printNumber = new PrintNumber2();
        Thread t0 = new Thread(() -> {
            printNumber.print(0);
        }, "A");
        Thread t1 = new Thread(() -> {
            printNumber.print(1);
        }, "B");
        Thread t2 = new Thread(() -> {
            printNumber.print(2);
        }, "C");
        t0.start();
        t1.start();
        t2.start();

    }

}
